import React, { CSSProperties } from "react";
import ReactDOM, { Root } from "react-dom/client";
import {Modal,Card,CloseButton,Button, Container, ListGroup, InputGroup, Form} from 'react-bootstrap';
import './popupdialog.css';

interface PopupRegisterInfo{
    id:string;
}

class PopupDialogProps{
    id?:string="popupalertroot";
    modalId?:string='popupalertmodal';
    headerTitle?:string="headerTitle";
    message?:string="some message displayed here";
    showCloseButton?:boolean=true;
    renderContent?:()=>JSX.Element;
    modalContentClass?:string;
    closeButtonTitle?:string;
    showCancelButton?:boolean=false;
    cancelButtonTitle?:string;
    cancelButtonPosition?:string;
}

class PopupDialogAction{
    title:string="Action Name";
    action?:React.MouseEventHandler;
    textStyle?:CSSProperties
}

const popupAlertDefault:PopupDialogProps = {
    id:"popupalertroot",
    modalId:"popupalertmodal",
    cancelButtonPosition:"start"
}

var renderer:any = null;

const PopupDialog = {
    register:(registerInfo:PopupRegisterInfo)=>{
        let alertContainer = document.getElementById(registerInfo.id);
        if(alertContainer == null){
            let body = document.getElementsByTagName("body")[0];
            alertContainer = document.createElement("div");
            alertContainer.className = 'invisibile';
            alertContainer.id = registerInfo.id;
            body.appendChild(alertContainer);
        }else{
            console.debug("already registered.");
        }
        return alertContainer;
    },
    showPopup:(popupInfo:PopupDialogProps=popupAlertDefault)=>{
        if(!renderer){
            let alertContainer = PopupDialog.register({id:popupInfo.id||"popupalertroot"});
            renderer = ReactDOM.hydrateRoot(alertContainer,null);
        }
        const closeModal = ()=> {
            renderer.render(null);
        }
        const contentClassName = popupInfo.modalContentClass || "modalContent-middle";
        renderer.render(popupInfo.renderContent? popupInfo.renderContent():<Modal id={popupInfo.modalId}
                            show={true}
                            size={"xl"}
                            fullscreen={'md-down'}
                            centered
                            dialogClassName="modalDialog"
                            contentClassName={contentClassName}
                    >
                       <Card id="card" style={{flex:1,width:"100%"}}>
                            {popupInfo.headerTitle && popupInfo.headerTitle.length > 0 ? <Card.Header>
                                <Card.Title>{popupInfo.headerTitle}</Card.Title>
                            </Card.Header>:null}
                            <Card.Body style={{flex:1,flexDirection:"column",display:"flex"}}>
                                <Card.Text>{popupInfo.message}</Card.Text>
                                <div style={{flex:1}}/>
                                <Button style={{width:80,height:40,alignSelf:"flex-end"}} onClick={closeModal}>OK</Button>
                            </Card.Body>
                    </Card>
        </Modal>)
    },
    showBSPopup:(popupInfo:PopupDialogProps=popupAlertDefault,onNext?:Function)=>{
        if(!renderer){
            let alertContainer = PopupDialog.register({id:popupInfo.id||"popupalertroot"});
            renderer = ReactDOM.createRoot(alertContainer);
        }
        const closeModal = ()=> {
            renderer.render(null);
            if(onNext){
                onNext()
            }
        }
        const onCancel = ()=> {
            renderer.render(null);
        }
        
        const btnLayout = popupInfo.cancelButtonPosition === "end" ? "flex-row justify-content-end" : "flex-row-reverse justify-content-start";

        renderer.render(popupInfo.renderContent? popupInfo.renderContent():<Modal 
            size="lg"
            aria-labelledby="custom-popup-modal-title-vcenter"
            centered
            show={true}
        >
            {popupInfo.headerTitle ?<Modal.Header>
             <Modal.Title id="custom-popup-modal-title-vcenter">
                {popupInfo.headerTitle}
                </Modal.Title>
            </Modal.Header>:null}
            <Modal.Body>
                <Container className="p-3">
                    <p>{popupInfo.message}</p>
                </Container>
            </Modal.Body>
            <Modal.Footer>
                <Container className={`d-flex p-0 ${btnLayout}`}>
                    <Button onClick={closeModal}>{popupInfo.closeButtonTitle || 'OK'} </Button>&nbsp;
                    {popupInfo.showCancelButton && <Button onClick={onCancel}>{popupInfo.cancelButtonTitle || 'Cancel'} </Button>}
                </Container>
            </Modal.Footer>
        </Modal>)
    },
    showInput:(title?:string,onConfirm?:Function,cancelTextStyle?:CSSProperties)=>{
        PopupDialog.showBSPopup({renderContent:()=>{
            var newValue = "";
            return (<Modal 
                size="lg"
                aria-labelledby="custom-popup-modal-title-vcenter"
                centered
                show={true}
                onHide={()=>{
                    PopupDialog.dismiss()
                }}
            >
                <Modal.Header closeButton style={{borderBottom:"none"}}>
                    <Form.Label className="me-2">{title}</Form.Label>
                </Modal.Header>
                <Modal.Body>
                    <Container fluid className="d-flex flex-column p-0 m-0">
                        <Form>
                            <Form.Control id="newname_input" type="input" 
                                placeholder="input new name here"
                                onChange={(e)=>{
                                    newValue = e.currentTarget.value;
                                }}
                                />
                        </Form>
                        <Button className="align-self-end mt-2" style={{minWidth:50}} onClick={()=>{
                            PopupDialog.dismiss();
                            if(newValue){
                                onConfirm && onConfirm(newValue);
                            }
                    }}>OK</Button>
                    </Container>
                </Modal.Body>
            </Modal>)
        }})
    },
    showUploadImage:(title?:string,onChange?:React.ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>,onConfirm?:Function,cancelTextStyle?:CSSProperties)=>{
        
        const clearInput = ()=> {
            var inputEle:any = document.getElementById("newname_input_image");
            if(inputEle){
                inputEle.value = "";
            }
        }

        PopupDialog.showBSPopup({renderContent:()=>{
            return (<Modal 
                size="lg"
                aria-labelledby="custom-popup-modal-title-vcenter"
                centered
                show={true}
                onHide={()=>{
                    PopupDialog.dismiss()
                }}
            >
                <Modal.Header closeButton style={{borderBottom:"none"}}>
                    <Form.Label className="me-2">{title}</Form.Label>
                </Modal.Header>
                <Modal.Body>
                    <Container fluid className="d-flex flex-column p-0 m-0">
                        <InputGroup style={{width:"100%"}}>
                            <Form>
                                <Form.Control id="newname_input_image" type="file" 
                                    placeholder="input new name here"
                                    onChange={onChange}
                                    accept=".jpeg,.png,.jpg,.webp,.svg"
                                    />
                            </Form>
                            <Button className="align-self-end" style={{minWidth:50}} onClick={()=>{
                                    onConfirm && onConfirm(clearInput);
                                }}>Upload</Button>
                        </InputGroup>
                        <Button className="align-self-end mt-3" style={{minWidth:50}} onClick={()=>{
                            PopupDialog.dismiss();
                        }}>Dismiss</Button>
                    </Container>
                </Modal.Body>
            </Modal>)
        }})
    },
    showRenameDialog:(oldname?:string,onConfirm?:Function,cancelTextStyle?:CSSProperties)=>{
        PopupDialog.showBSPopup({renderContent:()=>{
            var newValue = "";
            return (<Modal 
                size="lg"
                aria-labelledby="custom-popup-modal-title-vcenter"
                centered
                show={true}
                onHide={()=>{
                    PopupDialog.dismiss()
                }}
            >
                {oldname ?<Modal.Header closeButton>
                 <Modal.Title>
                    Rename
                </Modal.Title>
                </Modal.Header>:null}
                <Modal.Body>
                    <Container fluid className="d-flex flex-column p-0 m-0">
                        <p>Old name: {oldname}</p>
                        <br/>
                        <Form>
                            <InputGroup>
                                <Form.Text className="me-1">New Name:</Form.Text>
                                <Form.Control id="newname_input" type="input" 
                                    placeholder="input new name here"
                                    onChange={(e)=>{
                                        newValue = e.currentTarget.value;
                                    }}
                                    />
                            </InputGroup>
                        </Form>
                        <Button className="align-self-end mt-2" onClick={()=>{
                            PopupDialog.dismiss();
                            if(newValue){
                                onConfirm && onConfirm(newValue);
                            }
                    }}>OK</Button>
                    </Container>
                </Modal.Body>
            </Modal>)
        }})
    },
    showActions:(title?:string,actions?:Array<PopupDialogAction>,cancelTextStyle?:CSSProperties)=>{
        PopupDialog.showBSPopup({renderContent:()=>{
            return (<Modal 
                size="lg"
                aria-labelledby="custom-popup-modal-title-vcenter"
                centered
                show={true}
            >
                {title ?<Modal.Header>
                 <Modal.Title id="custom-popup-modal-title-vcenter">
                    {title}
                    </Modal.Title>
                </Modal.Header>:null}
                <Modal.Body>
                    <Container fluid className="p-0 m-0">
                        <ListGroup>
                            {actions?.map((item,index)=>{
                                return (<ListGroup.Item key={index.toString()} onClick={(e)=>{
                                    PopupDialog.dismiss();
                                    item.action && item.action(e);
                                }}>
                                   <p className="text-center" style={item.textStyle}>{item.title}</p> 
                                </ListGroup.Item>)
                            })}
                            <ListGroup.Item key={(actions?.length||10000).toString()} onClick={()=>{
                                PopupDialog.dismiss();
                            }}>
                                    <p className="text-center" style={cancelTextStyle||{color:'grayText'}}>{"Cancel"}</p> 
                                </ListGroup.Item>
                        </ListGroup>
                    </Container>
                </Modal.Body>
            </Modal>)
        }})
    },
    showBsError:(err:any)=>{
        PopupDialog.showBSPopup({message:err.message||err});
    },
    dismiss:(popupInfo:PopupDialogProps=popupAlertDefault)=>{
        if(!renderer){
            let alertContainer = PopupDialog.register({id:popupInfo.id||"popupalertroot"});
            renderer = ReactDOM.hydrateRoot(alertContainer,null);
        }
        renderer.render(null);
    }
}

export default PopupDialog;